<!-- JobPostForm.vue -->
<template>
  <el-dialog
    v-model="visible"
    width="900px"
    destroy-on-close
    :show-close="true"
    class="jobpost-dialog min-h-[70vh]"
  >
    <!-- 自定义头部：还原你给的“返回/保存草稿”风格 -->
    <template #header>
      <header class="bg-white py-3 px-4 flex items-center justify-between border-b border-gray-100">
        <div class="flex items-center space-x-3">
          <el-button link @click="visible=false">
            <el-icon><ArrowLeft /></el-icon>
            <span class="ml-1">返回</span>
          </el-button>
          <h1 class="text-xl font-bold text-gray-800">
            {{ mode==='create' ? '发布新岗位' : '编辑岗位' }}
          </h1>
        </div>
        <!-- <el-button type="info" plain class="!rounded-button whitespace-nowrap" :loading="submitting" @click="saveDraft">
          保存草稿
        </el-button> -->
      </header>
    </template>

    <!-- 主体内容（Tailwind 布局 + Element 表单校验/控件） -->
    <main class="py-6 px-4">
      <div class="bg-white rounded-xl shadow-sm p-6">
        <el-form ref="formEl" :model="form" :rules="rules" label-width="100px" class="w-full">
          <!-- 基本信息 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 mb-8">
            <!-- 岗位标题 -->
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                岗位标题 <span class="text-red-500">*</span>
              </label>
              <el-input
                v-model="form.title"
                placeholder="请输入岗位标题，如：Java后端实习生"
                size="large"
                clearable
                maxlength="128"
                show-word-limit
              />
            </div>

            <!-- 岗位类别（保持自由文本，避免改变数据结构约束） -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">岗位类别</label>
              <el-input v-model="form.category" placeholder="如：技术类 / 产品类" size="large" maxlength="64" />
            </div>

            <!-- 工作地点（location + 城市码） -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">工作地点</label>
              <el-input v-model="form.location" placeholder="详细地址，如 张江高科园区xx路xx号" size="large" maxlength="128" />
              <div class="text-xs text-gray-400 mt-1">城市码（如浦东新区 310115）</div>
              <el-input v-model="form.cityCode" placeholder="城市码" size="large" maxlength="16" class="mt-1" />
            </div>

            <!-- 学历要求 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">学历要求</label>
              <el-input v-model="form.eduReq" placeholder="如：本科 / 专科 / 不限" size="large" maxlength="32" />
            </div>

            <!-- 经验要求 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">经验要求</label>
              <el-input v-model="form.expReq" placeholder="如：不限 / 熟悉Java基础优先" size="large" maxlength="64" />
            </div>

            <!-- 薪资范围 + 单位 -->
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-2">薪资范围</label>
              <div class="flex items-center flex-wrap gap-2">
                <el-input-number v-model="form.salaryMin" :min="0" :max="9999999" controls-position="right" placeholder="最低" />
                <span class="text-gray-500">-</span>
                <el-input-number v-model="form.salaryMax" :min="0" :max="9999999" controls-position="right" placeholder="最高" />
                <el-select v-model="form.salaryUnit" size="large" class="w-36">
                  <el-option :value="1" label="元/月" />
                  <el-option :value="2" label="元/年" />
                  <el-option :value="3" label="元/天" />
                </el-select>
              </div>
              <div class="text-xs text-gray-400 mt-1">“最高薪资”不得小于“最低薪资”</div>
            </div>
          </div>

          <!-- 岗位描述 -->
          <div class="mb-8">
            <div class="flex justify-between items-center mb-2">
              <label class="block text-sm font-medium text-gray-700">
                岗位描述 <span class="text-red-500">*</span>
              </label>
              <span class="text-xs text-gray-500">{{ (form.description || '').length }}/5000</span>
            </div>
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="8"
              placeholder="请输入岗位描述，包括工作职责、任职要求、培养收获、加分项等"
              maxlength="5000"
              show-word-limit
            />
          </div>

          <!-- 标签 -->
          <div class="mb-8">
            <label class="block text-sm font-medium text-gray-700 mb-2">岗位标签</label>
            <div class="tag-input">
              <el-input
                v-model="tagInput"
                placeholder="回车添加，如：Java, SpringBoot"
                @keyup.enter="addTag"
                clearable
              />
              <div class="mt-2 flex flex-wrap gap-2 min-h-[28px]">
                <el-tag v-for="(t, i) in tags" :key="i" closable class="rounded-full" @close="removeTag(i)">
                  {{ t }}
                </el-tag>
                <span v-if="!tags.length" class="text-xs text-gray-400">暂无标签</span>
              </div>
            </div>
          </div>

          <!-- 时间与状态 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">发布时间</label>
              <el-date-picker
                v-model="form.publishTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择发布时间"
                class="w-full"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">到期时间</label>
              <el-date-picker
                v-model="form.expireTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择到期时间"
                class="w-full"
              />
            </div>
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
              <el-radio-group v-model="form.status">
                <el-radio :value="2">草稿</el-radio>
                <el-radio :value="1">上线</el-radio>
                <el-radio :value="0">下线</el-radio>
              </el-radio-group>
            </div>
            <div class="md:col-span-2">
              <label class="block text-sm font-medium text-gray-700 mb-2">备注</label>
              <el-input v-model="form.remark" maxlength="255" placeholder="仅内部可见，便于运营记录" />
            </div>
          </div>
        </el-form>

        <!-- 底部操作按钮（不改原有提交流程） -->
        <div class="flex justify-end space-x-3 pt-6 border-t border-gray-100">
          <el-button size="large" class="!rounded-button whitespace-nowrap" :disabled="submitting" @click="visible=false">
            取消
          </el-button>
          <el-button type="primary" size="large" class="!rounded-button whitespace-nowrap" :loading="submitting" @click="submit">
            {{ mode==='create' ? '发布岗位' : '保存修改' }}
          </el-button>
        </div>
      </div>
    </main>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import * as ElementPlus from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { createJobPost, updateJobPost, getJobPost } from '@/api/business/jobpost'
import type { JobPostVO } from '@/api/business/jobpost'

const ElMessage = (ElementPlus as any).ElMessage
const emit = defineEmits(['success'])

const visible = ref(false)
const mode = ref<'create'|'update'>('create')
const editingId = ref<number | null>(null)
const submitting = ref(false)
const formEl = ref()

// 表单数据（与后端字段对齐）
const form = reactive<JobPostVO>({
  title: '',
  category: '',
  location: '',
  cityCode: '',
  salaryMin: null,
  salaryMax: null,
  salaryUnit: 1,
  eduReq: '',
  expReq: '',
  description: '',
  publishTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  expireTime: '',
  status: 2,
  remark: ''
})

// 标签（最终落库到 tags，按需 JSON stringify）
const tags = ref<string[]>([])
const tagInput = ref('')

const addTag = () => {
  const t = tagInput.value.trim()
  if (!t) return
  if (!tags.value.includes(t)) tags.value.push(t)
  tagInput.value = ''
}
const removeTag = (i: number) => tags.value.splice(i, 1)

const rules = {
  title: [{ required: true, message: '请输入职位标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入岗位描述', trigger: 'blur' }],
  salaryMax: [{
    validator: (_r: any, _v: any, cb: any) => {
      if (form.salaryMin != null && form.salaryMax != null && (form.salaryMax as number) < (form.salaryMin as number)) {
        cb(new Error('最高薪资不能小于最低薪资'))
      } else cb()
    },
    trigger: 'change'
  }]
}

// 打开弹窗（父组件通过 ref 调用）
function open(m: 'create'|'update', record?: Partial<JobPostVO> & { id?: number }) {
  mode.value = m
  visible.value = true
  submitting.value = false
  editingId.value = null

  // 重置
  form.title = ''
  form.category = ''
  form.location = ''
  form.cityCode = ''
  form.salaryMin = null
  form.salaryMax = null
  form.salaryUnit = 1
  form.eduReq = ''
  form.expReq = ''
  form.description = ''
  form.publishTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  form.expireTime = ''
  form.status = 2
  form.remark = ''
  tags.value = []

  if (m === 'update' && record?.id) {
    editingId.value = record.id!
    // 若父级传来完整行，直接回显；否则兜底查详情
    if (record && record.title) {
      Object.assign(form, record)
      try {
        const arr = Array.isArray(record.tags)
          ? record.tags
          : (record.tags ? JSON.parse(record.tags as string) : [])
        tags.value = Array.isArray(arr) ? (arr as string[]) : []
      } catch { tags.value = [] }
    } else {
      getJobPost(editingId.value).then(({ data }) => {
        Object.assign(form, (data || {}) as JobPostVO)
        try {
          const arr = Array.isArray(data?.tags)
            ? (data as any).tags
            : (data?.tags ? JSON.parse(data.tags as any) : [])
          tags.value = Array.isArray(arr) ? arr : []
        } catch { tags.value = [] }
      })
    }
  }
}

// 保存草稿（仅置 status=2，然后复用原 submit 流程）
const saveDraft = async () => {
  form.status = 2
  await submit()
}

async function submit() {
  if (!formEl.value) return
  await (formEl.value as any).validate()
  submitting.value = true
  try {
    const payload: any = { ...form, sourceType: 1 }
    payload.tags = tags.value.length ? JSON.stringify(tags.value) : undefined

    if (mode.value === 'create') {
      await createJobPost(payload)
      ElMessage.success(form.status === 2 ? '草稿已保存' : '发布成功')
    } else {
      await updateJobPost(editingId.value as number, payload)
      ElMessage.success(form.status === 2 ? '草稿已保存' : '保存成功')
    }
    visible.value = false
    emit('success')
  } finally {
    submitting.value = false
  }
}

defineExpose({ open, editingId })
</script>

<style scoped>
/* 对话框头部轻微收紧 */
.jobpost-dialog :deep(.el-dialog__header) { padding: 0; }
.jobpost-dialog :deep(.el-dialog__body) { padding: 0; }

/* 微调 Element 默认 tag 外观以贴合卡片风格 */
:deep(.el-tag) { border: none; font-weight: 500; }
</style>
